package com.kernel.net;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

/****************************************
 * @name DataServer
 * @description
 * @author 黄彬恒
 * @since 2018/8/24
 ***************************************/
public class DataServer {
    public static void main(String[] args) throws IOException {
        int ports[] = {8000, 8001, 8002, 8003, 8004};// 表示五个监听端口
        Selector selector = Selector.open();
        for (int port : ports) {
            ServerSocketChannel initSer;
            initSer = ServerSocketChannel.open(); // 打开服务器的通道
            initSer.configureBlocking(false);// 服务器配置为非阻塞
            ServerSocket initSock = initSer.socket();
            InetSocketAddress address;
            address = new InetSocketAddress(port);// 实例化绑定地址
            initSock.bind(address);// 进行服务的绑定
            initSer.register(selector, SelectionKey.OP_ACCEPT);// 等待连接
            System.out.println("服务器运行，在" + port + "端口监听。");
        }
        // 要接收全部生成的key，并通过连接进行判断是否获取客户端的输出
        while (selector.select() > 0) {// 选择一组键，并且相应的通道已经就绪
            Set<SelectionKey> selectionKeys = selector.selectedKeys();// 取出全部生成的键
            for (SelectionKey key : selectionKeys) {
                if (key.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel client = server.accept();// 接收新连接
                    client.configureBlocking(false);// 配置为非阻塞
                    ByteBuffer outBuf = ByteBuffer.allocate(1024);
                    outBuf.put(("当前的时间为: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                            .getBytes("GBK"));// 向缓冲区中设置内容
                    outBuf.flip();
                    client.write(outBuf);// 输出内容
                    client.close();// 关闭
                }
            }
            selectionKeys.clear();// 清除全部的key
        }
    }
}
